<template>
  <!-- 添加或修改付款记录对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="基本信息" name="first">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="供应商名称" prop="supplierName">
                <el-input v-model="form.supplierName" placeholder="请输入供应商名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户行" prop="bankName">
                <el-input v-model="form.bankName" placeholder="请输入开户行"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="行号" prop="bankNo">
                <el-input v-model="form.bankNo" placeholder="请输入行号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="账号" prop="accountNo">
                <el-input v-model="form.accountNo" placeholder="请输入账号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="支付时间" prop="payTime">
                <el-date-picker clearable
                                v-model="form.payTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                placeholder="请选择支付时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款金额" prop="money">
                <el-input-number :precision="2" v-model="form.money" :max="apply.remainMoney" @change="selectApplyListByMoney"
                                 placeholder="请输入付款金额"/>
                <span style="color: red;">剩余金额：{{apply.remainMoney}}</span>&nbsp;&nbsp;&nbsp;
                <span style="color: green;" v-if="apply.shippingFee>0">运费：{{apply.shippingFee}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="付款凭证" prop="attachment">
                <file-upload v-model="form.attachment" :limit="5"></file-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <el-table border v-loading="loading"  :data="payApplyBuyDetailList" @selection-change="handleSelectionChange" ref="table"
              show-summary :summary-method="getSummaries">
      <el-table-column type="selection" width="60" align="center" :selectable="selectable"/>
      <el-table-column label="序号" type="index" align="center" width="50"></el-table-column>
      <el-table-column label="采购单号" align="center" prop="params.buyNos"/>
      <el-table-column label="产品名称" align="center" prop="goodsName" show-overflow-tooltip/>
      <el-table-column label="产品型号" align="center" prop="goodsModel"/>
      <el-table-column label="存货编码" align="center" prop="goodsCode"/>
      <el-table-column label="单价/吨价" align="center" prop="buyDetail.goodsBuyPrice"/>
      <el-table-column label="吨位" align="center" prop="buyDetail.dun"/>
      <el-table-column label="数量" align="center" prop="buyDetail.shengyu"/>
      <el-table-column label="源单金额" align="center" prop="buyDetail.goodsBuyTotal"/>
      <el-table-column label="已付金额" align="center" prop="payMoney"/>
      <el-table-column label="剩余付款" align="center" prop="payRemain"/>
      <el-table-column label="本次付款" align="center" prop="thisPayMoney" width="200">
        <template slot-scope="scope">
          <el-input-number :precision="4" v-model="scope.row.thisPayMoney" size="mini" :max="scope.row.payRemain"
                           placeholder="请输入本次付款"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="完成付款" prop="payStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_no" :value="scope.row.payStatus"/>
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {accAdd, accSub, addAction, getAction, getById, updateAction} from '@/api/manage';
import moment from 'moment';
import {parseTime} from "@/utils/common";

export default {
  name: "PayRecordForm",
  dicts: ['yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 付款申请单表格数据
      payApplyBuyDetailList: [],
      selectRows: [],
      // 查询参数
      queryParams: {
        pageSizeZero:true,
        type: null,
        buyId: null,
        invoiceCode: null,
        assessStatus: null,
        orderByColumn: "applyTime",
        isAsc: "desc"
      },
      activeName: "first",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      apply: {},
      // 表单校验
      rules: {
        supplierName: [{required: true, message: "请输入供应商名称", trigger: "blur"}],
        bankName: [{required: true, message: "请输入开户行", trigger: "blur"}],
        accountNo: [{required: true, message: "请输入银行账号", trigger: "blur"}],
        payTime: [{required: true, message: "请选择支付时间", trigger: "blur"}],
        money: [
          {required: true, message: "请输入申请付款金额", trigger: "blur"},
          {
            validator: this.moneyValidator,
            trigger: 'blur'
          }
        ],
      },
      url: {
        getById: '/payRecord/payRecord/',
        add: '/payRecord/payRecord/payAdd',
        edit: '/payRecord/payRecord/edit',
        payApplyBuyDetailList: '/payApplyBuyDetail/payApplyBuyDetail/list',
      },
    };
  },
  created() {
  },
  mounted() {
  },
  methods: {
    moneyValidator(rule, value, callback) {
      if (value === 0) {
        callback(new Error('付款金额不能为0'));
      } else {
        callback();
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        applyId: null,
        supplierId: null,
        supplierName: null,
        bankName: null,
        bankNo: null,
        accountNo: null,
        payTime: null,
        money: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加付款记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getById(this.url.getById, id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改付款记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.payApplyBuyDetails = this.selectRows;
      this.$refs["form"].validate(valid => {
        if (valid) {
          addAction(this.url.add, this.form).then(response => {
            this.$modal.msgSuccess("付款成功");
            this.open = false;
            this.$emit('ok');
          });
        }
      });
    },


    /** 新增按钮操作 */
    handleAddByApply(apply) {
      this.reset();
      this.open = true;
      this.title = "添加付款记录";
      this.apply = apply;
      this.form.applyId = apply.id;
      this.form.supplierId = apply.supplierId;
      this.form.supplierName = apply.supplierName;
      this.form.bankName = apply.bankName;
      this.form.bankNo = apply.bankNo;
      this.form.shippingFee = apply.shippingFee;
      this.form.accountNo = apply.accountNo;
      this.form.money = 0;
      this.form.payTime = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
      this.queryParams.payApplyId = apply.id;
      this.loading = false;
      this.getPayApplyBuyDetailList();
    },

    getPayApplyBuyDetailList() {
      this.loading = true;
      getAction(this.url.payApplyBuyDetailList, this.queryParams).then(response => {
        this.payApplyBuyDetailList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.selectRows = [...this.payApplyBuyDetailList];
      });
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length;
      this.selectRows = selection;
    },

    selectable(row, rowIndex) {
      // 根据row中的 payStatus 属性来决定是否禁用勾选框
      // return row.payStatus === '0';
    },

    // 已经弃用
    sumTotalMoney() {
      let money = 0;
      for (let j = 0; j < this.payApplyBuyDetailList.length; j++) {
        let flag = false;
        for (let i = 0; i < this.ids.length; i++) {
          if (this.ids[i] === this.payApplyBuyDetailList[j].id) {
            this.payApplyBuyDetailList[j].thisPayMoney = this.payApplyBuyDetailList[j].buyDetail.goodsBuyTotal;
            money = accAdd(money, this.payApplyBuyDetailList[j].buyDetail.goodsBuyTotal);
            flag = true;
          }
        }
        if (!flag) {
          this.payApplyBuyDetailList[j].thisPayMoney = 0;
        }
      }
      this.form.money = money;
    },


    selectApplyListByMoney(){
      let money = this.form.money;
      // 先清空 payRemain
      for (let j = 0; j < this.payApplyBuyDetailList.length; j++) {
        this.payApplyBuyDetailList[j].thisPayMoney = 0;
      }
      this.$refs.table.clearSelection();
      // let selectRows = [];
      for (let j = 0; j < this.payApplyBuyDetailList.length; j++) {
        if (money > 0) {
          if (this.payApplyBuyDetailList[j].payStatus === '0') {
            if (money >= this.payApplyBuyDetailList[j].payRemain) {
              this.payApplyBuyDetailList[j].thisPayMoney = this.payApplyBuyDetailList[j].payRemain;
              money = accSub(money, this.payApplyBuyDetailList[j].payRemain);
              this.$refs.table.toggleRowSelection(this.payApplyBuyDetailList[j], true);
            } else {
              this.payApplyBuyDetailList[j].thisPayMoney = money;
              money = 0;
              this.$refs.table.toggleRowSelection(this.payApplyBuyDetailList[j], true);
            }
          }
        }
      }
    },

    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }

        let values;
        if (column.property === "buyDetail.goodsBuyTotal") {
          values = data.map((item) => Number(item.buyDetail.goodsBuyTotal));
        } else {
          values = data.map((item) => Number(item[column.property]));
        }

        if (column.property === "payRemain" || column.property === "buyDetail.goodsBuyTotal" || column.property === "thisPayMoney") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },


  }
};
</script>
